package com.template.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.template.common.constant.ConstantPool;
import com.template.common.utils.SnowflakeIdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;


/**
 * @author mltong
 */
public class LogInterceptor implements HandlerInterceptor {


    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 删除LogId
        MDC.remove(ConstantPool.LOG_ID);
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String logId = request.getHeader(ConstantPool.LOG_ID);
        if(StringUtils.isEmpty(logId)) {
            logId = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + SnowflakeIdUtil.onlyId();
        }
        MDC.put(ConstantPool.LOG_ID, logId);
        return true;
    }
}